<template>
  <div>
    <!--      面包屑导航栏-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图-->
    <el-card>
      <!-- 添加按钮-->
      <el-row>
        <el-button type="primary">添加</el-button>
      </el-row>

      <el-table :data="roleList" border stripe style="margin-top: 20px">
        <!--   展开列：只需加type属性：expand-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!--通过数组形式给第一行加上边框，其他的加下边框,ventet类是将标签纵向居中,i1是索引-->
            <el-row
              :class="['bdbt', i1 === 0 ? 'bdtop' : '', 'venter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!--  渲染一级权限，加上一个箭头图标，col是列，一行总共24列-->
              <el-col :span="5">
                <!-- closable属性：带删除按钮，点击后会触发close事件，用来删除这个菜单-->
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.name }}</el-tag
                ><i class="el-icon-caret-right"></i>
              </el-col>
              <!--  渲染二级和三级权限-->
              <el-col :span="19">
                <!-- row:行，col：列，循环出子菜单，给每行添加一个上边框，去除重复的第一行上边框-->
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'venter']"
                >
                  <!--渲染二级权限-->
                  <el-col :span="6">
                    <!--  closable属性：带删除按钮，点击后会触发close事件，用来删除这个菜单-->
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.name }}</el-tag
                    ><i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="18">
                    <!--  三级权限，closable属性：带删除按钮，点击后会触发close事件，用来删除这个菜单-->
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.name }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column type="index" label="#"></el-table-column
        ><!-- 索引列-->
        <el-table-column label="角色名称" prop="rolename"></el-table-column>
        <el-table-column label="角色描述" prop="roledsc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="small"
              >编辑</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="small"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="small"
              @click="showSetRinghtDialog(scope.row)"
              >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--    权限分配菜单对话框-->
    <el-dialog
      title="权限分配"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
    <!-- 分配角色树形控件 -->
      <!--      树形控件,data:数据来源，props：数据对象,show-checkbox属性：显示多选框-->
      <!--      node-key属性：节点唯一标识属性，用id作为它的值-->
      <!--      default-expand-all：属性，展开所有节点-->
      <!--      default-checked-keys:默认选中节点的数组-->
      <!--      ref:添加引用，用来获取选中和半选中的id，分配权限-->
      <el-tree
        :data="rightsList"
        :props="treeprops"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      // 所有角色列表数据
      roleList: [
        {
          rolename: "主管",
          roledsc: "1",
          children: [
            {
              id: 1,
              name: "权限1",
              children: [
                {
                  id: 1,
                  name: "权限2",
                  children: [
                    { id: 5, name: "三级" },
                    { id: 5, name: "三级" },
                    { id: 5, name: "三级" },
                  ],
                },
                { id: 3, name: "二级" },
              ],
            },
          ],
        },
        {
          rolename: "组长",
          roledsc: "2",
          children: [
            {
              id: 1,
              name: "权限1",
              children: [
                { id: 1, name: "权限2", children: [{ id: 5, name: "三级" }] },
                { id: 3, name: "二级" },
              ],
            },
          ],
        },
        {
          rolename: "员工",
          roledsc: "3",
          children: [
            {
              id: 1,
              name: "权限1",
              children: [
                { id: 1, name: "权限2", children: [{ id: 5, name: "三级" }] },
                { id: 3, name: "二级" },
              ],
            },
          ],
        },
      ],
      // 控制点击分配权限对话框显示
      setRightDialogVisible: false,
      //所有权限的数据
      rightsList: [
        {
          label: "一级 1",
          children: [
            {
              label: "二级 1-1",
              children: [
                {
                  label: "三级 1-1-1",
                },
              ],
            },
          ],
        },
        {
          label: "一级 2",
          children: [
            {
              label: "二级 2-1",
              children: [
                {
                  label: "三级 2-1-1",
                },
              ],
            },
            {
              label: "二级 2-2",
              children: [
                {
                  label: "三级 2-2-1",
                },
              ],
            },
          ],
        },
      ],
      //树形控件属性绑定对象，label是指定数据名称，与后端一致，此处为模拟数据
      treeprops: { label: "label", children: "children" },
      // 默认展开选中节点的数组，根据后端id
      defkeys: [1, 2, 3],
      //当前即将分配权限的角色id
      roleId: [],
    };
  },

  created() {
    this.getRoleList();
  },

  methods: {
    // 获取所有数据
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");
      if (res.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.roleList = res.data;
    },

    // 根据id删除菜单，添加提示框
    async removeRightById(role, rightid) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => {
        return error;
      });
      if (confirmResult !== "confirm") {
        return this.$message.info("取消删除");
      }
      // 点击确定按钮后,请求接口，获取返回的状态码
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightid}`
      );
      if (res.status !== 200) {
        return this.$message.error("删除权限失败");
      }
      // 获取成功重新请求数据，刷新页面
      //this.getRoleList()重新刷新用户体验不好
      //给子菜单重新赋值，菜单就不会关闭，显示更直观
      role.children = res.data;
    },

    //分配权限
    async showSetRinghtDialog(role) {
      this.roleId = role.id;

      //获取权限列表,返回树状结构
      const { data: res } = await this.$http.get("rights/tree");
      if (res.status !== 200) {
        return this.$message.error("获取权限列表失败");
      }
      // 权限列表赋值
      this.rightsList = res.data;
      //递归三级节点id
      this.getLeafKeys(role, this.defkeys);
      //打开权限分配会话框
      this.setRightDialogVisible = true;
    },

    // 通过递归形式，获取角色下所有的三级权限的id，并保存到defkeys数组中
    getLeafKeys(node, arr) {
      //如果当前node没有children，说明是三级权限,把三级权限id放到数组中
      if (!node.children) {
        return arr.push(node.id);
      }
      // 如果不是三级权限，通过循环递归把节点循环出来，并把id保存到选中的defkeys
      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    // 监听对话框关闭，因为每次点击会往数组添加id，因此数组内容会越来越多，
    // 导致其他角色也会有权限，所以每次关闭后先清空
    setRightDialogClosed() {
      this.defkeys = [];
    },

    // 点击为角色分配权限：通过$ref引用
    // getCheckedKeys()：获取选中节点的key的数组
    //getHalfCheckedKeys():获取半选中节点的key的数组
    //...将两个数组合并成一个数组
    allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      // join（）：数组转为字符串，通过逗号隔开
      const idStr = keys.join(",");
      this.$http.post(`roles/${roleId}/rights`, { ids: idStr });
    },
  },
};
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbt {
  border-bottom: 1px solid #eee;
}
.venter {
  display: flex;
  align-items: center;
}
</style>
